//
// Copyright 2017 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//

#import "TSGroupThread.h"
#import <SignalServiceKit/SignalServiceKit-Swift.h>

NS_ASSUME_NONNULL_BEGIN

NSString *const TSGroupThreadAvatarChangedNotification = @"TSGroupThreadAvatarChangedNotification";
NSString *const TSGroupThread_NotificationKey_UniqueId = @"TSGroupThread_NotificationKey_UniqueId";

#pragma mark -

@implementation TSGroupThread

// --- CODE GENERATION MARKER

// This snippet is generated by /Scripts/sds_codegen/sds_generate.py. Do not manually edit it, instead run
// `sds_codegen.sh`.

// clang-format off

- (instancetype)initWithGrdbId:(int64_t)grdbId
                      uniqueId:(NSString *)uniqueId
   conversationColorNameObsolete:(NSString *)conversationColorNameObsolete
                    creationDate:(nullable NSDate *)creationDate
             editTargetTimestamp:(nullable NSNumber *)editTargetTimestamp
              isArchivedObsolete:(BOOL)isArchivedObsolete
          isMarkedUnreadObsolete:(BOOL)isMarkedUnreadObsolete
       lastDraftInteractionRowId:(uint64_t)lastDraftInteractionRowId
        lastDraftUpdateTimestamp:(uint64_t)lastDraftUpdateTimestamp
            lastInteractionRowId:(uint64_t)lastInteractionRowId
          lastSentStoryTimestamp:(nullable NSNumber *)lastSentStoryTimestamp
       lastVisibleSortIdObsolete:(uint64_t)lastVisibleSortIdObsolete
lastVisibleSortIdOnScreenPercentageObsolete:(double)lastVisibleSortIdOnScreenPercentageObsolete
         mentionNotificationMode:(TSThreadMentionNotificationMode)mentionNotificationMode
                    messageDraft:(nullable NSString *)messageDraft
          messageDraftBodyRanges:(nullable MessageBodyRanges *)messageDraftBodyRanges
          mutedUntilDateObsolete:(nullable NSDate *)mutedUntilDateObsolete
     mutedUntilTimestampObsolete:(uint64_t)mutedUntilTimestampObsolete
           shouldThreadBeVisible:(BOOL)shouldThreadBeVisible
                   storyViewMode:(TSThreadStoryViewMode)storyViewMode
                      groupModel:(TSGroupModel *)groupModel
{
    self = [super initWithGrdbId:grdbId
                        uniqueId:uniqueId
     conversationColorNameObsolete:conversationColorNameObsolete
                      creationDate:creationDate
               editTargetTimestamp:editTargetTimestamp
                isArchivedObsolete:isArchivedObsolete
            isMarkedUnreadObsolete:isMarkedUnreadObsolete
         lastDraftInteractionRowId:lastDraftInteractionRowId
          lastDraftUpdateTimestamp:lastDraftUpdateTimestamp
              lastInteractionRowId:lastInteractionRowId
            lastSentStoryTimestamp:lastSentStoryTimestamp
         lastVisibleSortIdObsolete:lastVisibleSortIdObsolete
lastVisibleSortIdOnScreenPercentageObsolete:lastVisibleSortIdOnScreenPercentageObsolete
           mentionNotificationMode:mentionNotificationMode
                      messageDraft:messageDraft
            messageDraftBodyRanges:messageDraftBodyRanges
            mutedUntilDateObsolete:mutedUntilDateObsolete
       mutedUntilTimestampObsolete:mutedUntilTimestampObsolete
             shouldThreadBeVisible:shouldThreadBeVisible
                     storyViewMode:storyViewMode];

    if (!self) {
        return self;
    }

    _groupModel = groupModel;

    return self;
}

// clang-format on

// --- CODE GENERATION MARKER

- (nullable instancetype)initWithCoder:(NSCoder *)coder
{
    return [super initWithCoder:coder];
}

- (instancetype)initWithGroupModel:(TSGroupModelV2 *)groupModel
{
    OWSAssertDebug(groupModel);
    OWSAssertDebug(groupModel.groupId.length > 0);
#ifdef DEBUG
    for (SignalServiceAddress *address in groupModel.groupMembers) {
        OWSAssertDebug(address.isValid);
    }
#endif

    NSString *uniqueIdentifier = [[self class] defaultThreadIdForGroupId:groupModel.groupId];
    self = [super initWithUniqueId:uniqueIdentifier];
    if (!self) {
        return self;
    }

    _groupModel = groupModel;

    return self;
}

- (NSArray<SignalServiceAddress *> *)recipientAddressesWithTransaction:(DBReadTransaction *)transaction
{
    NSMutableArray<SignalServiceAddress *> *groupMembers = [self.groupModel.groupMembers mutableCopy];
    if (groupMembers == nil) {
        return @[];
    }

    [groupMembers removeObject:[TSAccountManagerObjcBridge localAciAddressWith:transaction]];

    return [groupMembers copy];
}

- (NSString *)groupNameOrDefault
{
    return self.groupModel.groupNameOrDefault;
}

+ (NSString *)defaultGroupName
{
    return OWSLocalizedString(@"NEW_GROUP_DEFAULT_TITLE", @"");
}

#pragma mark -

- (void)anyWillInsertWithTransaction:(DBWriteTransaction *)transaction
{
    [super anyWillInsertWithTransaction:transaction];
    [self updateGroupMemberRecordsWithTransaction:transaction];
}

- (void)anyWillUpdateWithTransaction:(DBWriteTransaction *)transaction
{
    [super anyWillUpdateWithTransaction:transaction];

    // We used to update the group member records here, but there are many updates that don't touch membership.
    // Now it's done explicitly where we update the group model, and not for other updates.
}

- (void)anyDidInsertWithTransaction:(DBWriteTransaction *)transaction
{
    [super anyDidInsertWithTransaction:transaction];

    OWSLogInfo(@"Inserted group thread: %@", self.groupId.hexadecimalString);
}

@end

NS_ASSUME_NONNULL_END
